package com.example.martian.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 */
@Component
public class FileUtil {

    @Value("${physicspath}")
    private String physicsPath;

    @Value("${netpath}")
    private String netpath;

    /**
     * folderName-文件夹名称 fileName-文件名称 File sourceFile-源文件
     */
    public String saveFile(String folderName, String fileName, MultipartFile sourceFile) {
        String newfilepath = physicsPath + folderName + "/" + getFileName(fileName) + ".jpg";    //新的文件路径
        //将图片保存到服务器
        saveFile(sourceFile,newfilepath);
        return newfilepath.replace(physicsPath, netpath);
    }

    public String getFileName(String identity) {
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatDate = format.format(d);
        String str = "";
        for (int i = 0; i < 5; i++) {
            int n = (int) (Math.random() * 90) + 10;
            str += n;
        }
        return formatDate + str + identity;
    }

    /**
     * folderName-文件夹名称 fileName-文件名称 bytes字节
     */
    public String saveFile(String folderName, String fileName, byte[] bytes) {
        String newfilepath = physicsPath + folderName + "/" + getFileName(fileName) + ".jpg";    //新的文件路径
        //将图片保存到服务器硬盘
        saveFile(bytes, newfilepath);
        return newfilepath.replace(physicsPath, netpath);

    }

    /*
     * 将输入流转换为字节
     */
    public byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    /**
     * 保存文件
     * 返回值:String
     */
    public void saveFile(MultipartFile oldfile, String newFilePath) {
        try {
            //如果没有就新建
            File newFile = new File(newFilePath);
            //获取父目录
            File fileParent = newFile.getParentFile();
            //如果父目录不存在那么创建
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            //然后创建文件
            newFile.createNewFile();
            writeFile(oldfile, newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //byte数组到图片到硬盘上
    public void saveFile(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) return;
        try {
            //如果没有就新建
            File newFile = new File(path);
            //获取父目录
            File fileParent = newFile.getParentFile();
            //如果父目录不存在那么创建
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
	 	   /* FileImageOutputStream imageOutput = new FileImageOutputStream(newFile);//打开输入流
	 	    imageOutput.write(data, 0, data.length);//将byte写入硬盘
	 	    imageOutput.close();*/
            FileOutputStream fout = new FileOutputStream(path);
            fout.write(data);
            fout.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static final int BUFFER_SIZE = 30 * 1024;

    /**
     * 写入文件
     * 返回值:void
     */
    private void writeFile(MultipartFile src, File dst) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream((File) src), BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
                byte[] buffer = new byte[BUFFER_SIZE];
                int i;
                while ((i = in.read(buffer)) > 0) {
                    out.write(buffer, 0, i);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
